package com.unf.edu.rms.controller.student;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.unf.edu.rms.controller.userlogin.UserLoginController;
import com.unf.edu.rms.controller.users.RMSBaseController;
import com.unf.edu.rms.controller.validation.StudentValidator;
import com.unf.edu.rms.dao.Student;
import com.unf.edu.rms.dao.Thesis;
import com.unf.edu.rms.dao.Faculty;
import com.unf.edu.rms.dao.ThesisCommittee;
import com.unf.edu.rms.service.StudentService;
import com.unf.edu.rms.service.ThesisService;
import com.unf.edu.rms.service.FacultyService;
import com.unf.edu.rms.util.RMSConstants;

@Controller
public class StudentController extends RMSBaseController{
	
	@Autowired
	private ThesisService thesisService;
	@Autowired
	private StudentService studentService;
	@Autowired
	private UserLoginController userLoginController;
	@Autowired
	private FacultyService facultyService;
	
	@RequestMapping("/viewStudentList")
	public String viewStudentList(Model model) {
		System.out.println("StudentController.viewStudent()==========");
		if(userLoginController.checkValidateSession()==0){
			return "redirect:Dashboard.html";
		}
		List<Student> studentList = studentService.viewStudentTable();
		
		List<Thesis> thesisList = thesisService.getThesisList();
		
		for(Thesis t:thesisList){
			Set<ThesisCommittee> thesisCommittees = t.getThesisCommittees();
			for(ThesisCommittee committee:thesisCommittees)
			{
				t.setThesisChairId(Integer.toString(committee.getFacultyByCommitteeChair().getFacultyId()));
			}
			for(Student student:studentList){
				if(student.getStudentId().equals(t.getStudent().getStudentId())){
					student.setThesisChairId(t.getThesisChairId());
				}
			}
		}
		
		model.addAttribute("studentList", studentList);
		return RMSConstants.STUDENT_VIEW;
		
	}
	
	@RequestMapping("/printStudentList")
	public String printStudentList(Model model) {
		System.out.println("StudentController.printStudentList()==========");
		if(userLoginController.checkValidateSession()==0){
			return "redirect:Dashboard.html";
		}
		List<Student> studentList = studentService.viewStudentTable();
		model.addAttribute("studentList", studentList);
		return RMSConstants.STUDENT_LIST_PRINT;
		
	}
	
	@RequestMapping(value = "/viewNewStudent", method = RequestMethod.POST)
	public String viewNewStudent(@ModelAttribute("student") Student student,Model model) {
		
		if(userLoginController.checkValidateSession()==0){
			return "redirect:Dashboard.html";
		}
		List<Student> studentList = studentService.viewStudentTable();
		List<Faculty> facultyList = facultyService.getFacultyList();
		Map<Integer,String> nNumberMap = new HashMap<Integer, String>();
		int i = 0;
		for(Student studentx:studentList)
		{
			if(studentx.getNnumber() != null && studentx.getNnumber() != ""){
				nNumberMap.put(i++,studentx.getNnumber());
			}
		}
		
		for(Faculty facultyx:facultyList)
		{
			if(facultyx.getNnumber() != null && facultyx.getNnumber() != ""){
				nNumberMap.put(i++, facultyx.getNnumber());
			}
		}
		model.addAttribute("nNumberMap", nNumberMap);
		model.addAttribute("studentList", studentList);
		
		return RMSConstants.ADD_STUDENT_VIEW;
	}
	
	@RequestMapping(value = "/addNewStudent", method = RequestMethod.POST)
	public String addNewStudent(@ModelAttribute("student") Student student,BindingResult bindingResult, Model model){
		

		StudentValidator studentValidator = new StudentValidator();
		studentValidator.validate(student, bindingResult);
		
		//Validate the E-mail Address to ensure that it is valid
		if(!checkEmail(student.getEmail())){
			bindingResult.rejectValue("email", "error.email.invalid");
		}
		
		if(!bindingResult.hasErrors()){
			studentService.addNewStudent(student);
			System.out.println("StudentControler.addNewStudent()==========");

			List<Student> studentList = studentService.viewStudentTable();
			
			model.addAttribute("studentList", studentList);
			
			return RMSConstants.STUDENT_VIEW;
		}
		else{

			List<Student> studentList = studentService.viewStudentTable();
			List<Faculty> facultyList = facultyService.getFacultyList();
			
			Map<Integer,String> nNumberMap = new HashMap<Integer, String>();
			int i = 0;
			for(Student studentx:studentList)
			{
				if(studentx.getNnumber() != null && studentx.getNnumber() != ""){
					nNumberMap.put(i++,studentx.getNnumber());
				}
			}
			
			for(Faculty facultyx:facultyList)
			{
				if(facultyx.getNnumber() != null && facultyx.getNnumber() != ""){
					nNumberMap.put(i++, facultyx.getNnumber());
				}
			}
			model.addAttribute("nNumberMap", nNumberMap);
			return RMSConstants.ADD_STUDENT_VIEW;
		}
	}
	
	@RequestMapping(value = "/viewExistingStudent", method = RequestMethod.POST)
	public String viewExitingStudent(@RequestParam(required=true) int studentId,Model model) {
		
		if(userLoginController.checkValidateSession()==0){
			return "redirect:Dashboard.html";
		}
		Student student = studentService.getStudentById(studentId);
		model.addAttribute("student",student);
		
		List<Student> studentList = studentService.viewStudentTable();
		List<Faculty> facultyList = facultyService.getFacultyList();
		
		Map<Integer,String> nNumberMap = new HashMap<Integer, String>();
		int i = 0;
		for(Student studentx:studentList)
		{
			if(studentx.getNnumber() != null && studentx.getNnumber() != ""){
				nNumberMap.put(i++,studentx.getNnumber());
			}
		}
		
		for(Faculty facultyx:facultyList)
		{
			if(facultyx.getNnumber() != null && facultyx.getNnumber() != ""){
				nNumberMap.put(i++, facultyx.getNnumber());
			}
		}
		model.addAttribute("nNumberMap", nNumberMap);
		
		return RMSConstants.ADD_STUDENT_VIEW;
	}
	
	@RequestMapping(value = "/printStudentDetails", method = RequestMethod.POST)
	public String printStudentDetails(@RequestParam(required=true) int studentId,Model model) {
		
		if(userLoginController.checkValidateSession()==0){
			return "redirect:Dashboard.html";
		}
		Student student = studentService.getStudentById(studentId);
		model.addAttribute("student",student);
		return RMSConstants.STUDENT_DETAILS_PRINT;
	}
	
	@RequestMapping(value = "/updateStudent", method = RequestMethod.POST)
	public String updateStudent(@RequestParam(required=true) int studentId,@ModelAttribute("student") Student student, BindingResult bindingResult, Model model) {
		
		student.setStudentId(studentId);
		StudentValidator studentValidator = new StudentValidator();
		studentValidator.validate(student, bindingResult);
		//Validate the E-mail Address to ensure that it is valid
		if(!checkEmail(student.getEmail())){
			bindingResult.rejectValue("email", "error.email.invalid");
		}
		if(!bindingResult.hasErrors()){
			studentService.updateStudent(student);
			return "redirect:viewStudentList.html";
		}
		else{
			return RMSConstants.ADD_STUDENT_VIEW;
		}
		
	}
	
	//This Method checks the email string against the regular expression that forms a standard email address
	public boolean checkEmail(String email)
	{
		String emailPattern = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
		+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
		Pattern pattern = Pattern.compile(emailPattern);
		Matcher matcher = pattern.matcher(email);
		System.out.println("Email Address: " + email + "    Is it valid?! " + matcher.matches());
		return matcher.matches();
	}
		
	@RequestMapping(value = "/viewStudentDetails", method = RequestMethod.POST)
    public String viewStudentDetails(@RequestParam(required=true) int studentId, Model model){
		if(userLoginController.checkValidateSession()==0){
			return "redirect:Dashboard.html";
		}
		List<Thesis> thesisList = thesisService.getThesisList();
		Thesis studentThesis = null;
		for(int i = 0; i < thesisList.size(); i++){
			if(thesisList.get(i).getStudent().getStudentId()==studentId){
				studentThesis = thesisList.get(i);
				System.out.println(studentThesis.getStudent().getStudentId());
			}
		}
		Student student = studentService.getStudentById(studentId);
        model.addAttribute("student", student);
        model.addAttribute("studentThesis", studentThesis);
        return RMSConstants.STUDENT_DETAILS_VIEW;
    }
}
